import * as React from 'react';
import dayjs from 'dayjs';
import { useSearchParams, useNavigate } from 'react-router-dom';
import Header from '@/commonComponents/header/Header';
import Nav from '@/commonComponents/nav/Nav';
import { h0 } from '@/utils/fp';
import useNav from '@/utils/hooks/useNav';
import { useAppSelector, useAppDispatch } from '@/app/hooks';
import { selectQuery, getQueryAsync } from './indexSlice';
import List from './components/list/index';
import Bottom from './components/bottom/';
import type { ListItemProps } from './types';
import './index.module.scss';

const { useEffect, memo, useState } = React;

function Query() {
  const [params] = useSearchParams();
  const from = params.get('from');
  const to = params.get('to');
  const date = params.get('date');
  const [highSpeed, setTighSpeed] = useState<boolean>(
    params.get('highSpeed') === 'true'
  );
  const [haveTicket, setHaveTicket] = useState(false);
  const [timeSort, setTimeSort] = useState(0); //0按早晚1耗时
  const tempDepartDate = h0(dayjs(date).valueOf());
  const [departDate, setDepartDate] = useState(tempDepartDate);
  const [trainList, setTrainList] = useState<ListItemProps[]>([]);
  const nextDate = () => {
    setDepartDate(h0(departDate) + 86400 * 1000);
  };
  const prevDate = () => {
    setDepartDate(h0(departDate) - 86400 * 1000);
  };
  // 回到上一页
  const navigate = useNavigate();
  const back = () => {
    navigate(-1);
  };
  const { isPrevDisabled, isNextDisabled, prev, next } = useNav(
    departDate,
    prevDate,
    nextDate
  );
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(
      getQueryAsync({
        from,
        to,
        date,
        highSpeed,
        haveTicket,
        timeSort,
      })
    );
  }, [from, to, date, highSpeed, haveTicket, timeSort]);
  const query = useAppSelector(selectQuery);
  const { trains } = query;

  useEffect(() => {
    setTrainList(trains);
  }, [trains]);
  return (
    <div styleName="query-box">
      <Header title={`${from}-${to}`} onBack={back} />
      <div styleName="query-box-con">
        <Nav
          date={departDate}
          isPrevDisabled={isPrevDisabled}
          isNextDisabled={isNextDisabled}
          prev={prev}
          next={next}
        />
        <List list={trainList} />
      </div>
      <Bottom
        highSpeed={highSpeed}
        haveTicket={haveTicket}
        timeSort={timeSort}
        changeData={setTrainList}
        changeTighSpeed={setTighSpeed}
        changeHaveTicket={setHaveTicket}
        changeTimeSort={setTimeSort}
        trains={trainList}
      ></Bottom>
    </div>
  );
}

export default memo(Query);
